<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="600px" :title="`${drawerProps.title}模块`">
    <el-form
      ref="ruleFormRef"
      label-width="120px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="模块名称" prop="name">
        <el-input v-model="drawerProps.row!.name" clearable></el-input>
      </el-form-item>

      <el-form-item label="所属模块" prop="pid">
        <cascader-select
          data-key="module"
          :request-api="() => apiService.findTree('module', {}, { sort: { sort: 1 }, fields: ['_id', 'name', 'pid'] })"
          :config="{ label: 'name', value: '_id', checkStrictly: true }"
          v-model:item-value="drawerProps.row!.pid"
        ></cascader-select>
      </el-form-item>

      <el-form-item label="所属产品" prop="productId">
        <common-select
          data-key="product"
          placeholder="请选择产品"
          :request-api="() => apiService.find('product', {}, { fields: ['_id', 'name'], sort: { name: 1 } })"
          :config="{ value: '_id', label: 'name' }"
          v-model="drawerProps.row!.productId"
        ></common-select>
      </el-form-item>

      <el-form-item label="模块描述" prop="note">
        <el-input v-model="drawerProps.row!.note" type="textarea" :rows="3" clearable></el-input>
      </el-form-item>

      <el-form-item label="重要性" prop="important">
        <common-select
          data-key="MODULE_IMPORTANT"
          placeholder="请选择重要性"
          :request-api="() => apiService.findClassify('MODULE_IMPORTANT')"
          v-model="drawerProps.row!.important"
        ></common-select>
      </el-form-item>

      <el-form-item label="平台支持" prop="platforms">
        <el-checkbox-group v-model="platforms">
          <el-checkbox label="manage">后台管理</el-checkbox>
          <el-checkbox label="app">App端</el-checkbox>
          <el-checkbox label="pc">PC端</el-checkbox>
          <el-checkbox label="web">Web端</el-checkbox>
          <el-checkbox label="pad">Pad端</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="产品负责人" prop="po">
        <user-dialog-select v-model="poUserIds" multiple placeholder="请选择产品负责人"></user-dialog-select>
      </el-form-item>

      <el-form-item label="UI负责人" prop="ui">
        <user-dialog-select v-model="uiUserIds" multiple placeholder="请选择UI负责人"></user-dialog-select>
      </el-form-item>

      <el-form-item label="测试负责人" prop="test">
        <user-dialog-select v-model="testUserIds" multiple placeholder="请选择测试负责人"></user-dialog-select>
      </el-form-item>

      <el-form-item label="运维负责人" prop="om">
        <user-dialog-select v-model="omUserIds" multiple placeholder="请选择运维负责人"></user-dialog-select>
      </el-form-item>

      <el-form-item label="开发负责人" prop="dev">
        <user-dialog-select v-model="devUserIds" multiple placeholder="请选择开发负责人"></user-dialog-select>
      </el-form-item>

      <el-form-item label="模块状态" prop="state">
        <common-select
          data-key="DATA_STATE"
          placeholder="请选择状态"
          :request-api="() => apiService.findClassify('DATA_STATE')"
          v-model="drawerProps.row!.state"
        ></common-select>
      </el-form-item>

      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="drawerProps.row!.sort" :min="0" controls-position="right"></el-input-number>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="ModuleDrawer">
import { ref, reactive, watch } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Module } from "@/api/types/base";
import { useUserStore } from "@/stores/modules/user";
import userDialogSelect from "@/components/SelectFilter/user-dialog-select.vue";
import apiService from "@/api/services/apiService";
import commonSelect from "@/components/SelectFilter/common-select.vue";
import cascaderSelect from "@/components/SelectFilter/cascader-select.vue";

const userStore = useUserStore();
const rules = reactive({
  name: [{ required: true, message: "请输入模块名称" }],
  productId: [{ required: true, message: "请选择所属产品" }]
});

interface DrawerProps {
  title: string;
  tbName: string;
  isView: boolean;
  row: Partial<Module>;
  api?: (tabName: string, params: any) => Promise<any>;
  getTableList?: () => void;
}

// 平台支持选项
const platforms = ref<string[]>([]);

// 用户选择相关的响应式数据（直接使用用户ID数组）
const poUserIds = ref<string[]>([]);
const uiUserIds = ref<string[]>([]);
const testUserIds = ref<string[]>([]);
const omUserIds = ref<string[]>([]);
const devUserIds = ref<string[]>([]);

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  tbName: "",
  row: {}
});

// 监听平台支持选项变化，同步到表单数据
watch(
  platforms,
  newVal => {
    if (drawerProps.value.row) {
      drawerProps.value.row.manage = newVal.includes("manage");
      drawerProps.value.row.app = newVal.includes("app");
      drawerProps.value.row.pc = newVal.includes("pc");
      drawerProps.value.row.web = newVal.includes("web");
      drawerProps.value.row.pad = newVal.includes("pad");
    }
  },
  { deep: true }
);

// 监听表单数据变化，同步到平台支持选项
watch(
  () => drawerProps.value.row,
  newVal => {
    if (newVal) {
      const selectedPlatforms: string[] = [];
      if (newVal.manage) selectedPlatforms.push("manage");
      if (newVal.app) selectedPlatforms.push("app");
      if (newVal.pc) selectedPlatforms.push("pc");
      if (newVal.web) selectedPlatforms.push("web");
      if (newVal.pad) selectedPlatforms.push("pad");
      platforms.value = selectedPlatforms;
    }
  },
  { deep: true }
);

// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps) => {
  drawerProps.value = params;
  // 初始化平台支持选项
  const selectedPlatforms: string[] = [];
  if (params.row.manage) selectedPlatforms.push("manage");
  if (params.row.app) selectedPlatforms.push("app");
  if (params.row.pc) selectedPlatforms.push("pc");
  if (params.row.web) selectedPlatforms.push("web");
  if (params.row.pad) selectedPlatforms.push("pad");
  platforms.value = selectedPlatforms;

  // 初始化用户选择数据（直接使用用户ID数组）
  if (params.row._id) {
    // 编辑模式，直接使用已有的用户ID数组
    poUserIds.value = params.row.po || [];
    uiUserIds.value = params.row.ui || [];
    testUserIds.value = params.row.test || [];
    omUserIds.value = params.row.om || [];
    devUserIds.value = params.row.dev || [];
  } else {
    // 新增模式，初始化为空数组
    poUserIds.value = [];
    uiUserIds.value = [];
    testUserIds.value = [];
    omUserIds.value = [];
    devUserIds.value = [];
  }

  drawerVisible.value = true;
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      // 直接使用用户ID数组存储（无需转换）
      if (drawerProps.value.row) {
        drawerProps.value.row.po = poUserIds.value;
        drawerProps.value.row.ui = uiUserIds.value;
        drawerProps.value.row.test = testUserIds.value;
        drawerProps.value.row.om = omUserIds.value;
        drawerProps.value.row.dev = devUserIds.value;
      }

      drawerProps.value.row.createUser = userStore.userInfo.userName;
      drawerProps.value.row.createDate = new Date();
      await drawerProps.value.api!(drawerProps.value.tbName, drawerProps.value.row);
      ElMessage.success({ message: `${drawerProps.value.title}模块成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
      ElMessage.error("操作失败");
    }
  });
};

defineExpose({
  acceptParams
});
</script>
